package ycj.learn.netty;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class TestSelector {
    public static void main(String[] args) {
        try {
            Selector selector = Selector.open();

            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);

            ssc.register(selector, SelectionKey.OP_ACCEPT, null);

            ssc.bind(new InetSocketAddress(8848));

            while (true) {
                selector.select();
                for (SelectionKey key : selector.selectedKeys()) {
                    if (key.isAcceptable()) {
                        ServerSocketChannel channel = (ServerSocketChannel) key.channel();

                        SocketChannel accept = channel.accept();
                        accept.configureBlocking(false);
                        accept.register(selector, SelectionKey.OP_READ, null);

                        /* selectedKey 不会自动删除 需要手动删除*/
                        selector.selectedKeys().remove(key);
                    } else if (key.isReadable()) {
                        try {
                            SocketChannel channel = (SocketChannel) key.channel();

                            ByteBuffer buffer = ByteBuffer.allocate(1 << 4);
                            while (-1 != channel.read(buffer)) {
                                buffer.flip();
                                while (buffer.hasRemaining()) {
                                    System.out.print(buffer.get());
                                }
                                buffer.flip();
                            }
                        }catch (Exception e){
                            key.cancel();
                        }
                    }
                }
            }
        } catch (Exception e) {
            /*do nothing*/
        }
    }
}
